package com.atguigu.lease.web.admin.controller.apartment;


import com.atguigu.lease.common.result.Result;
import com.atguigu.lease.model.entity.AttrKey;
import com.atguigu.lease.model.entity.AttrValue;
import com.atguigu.lease.model.entity.BaseEntity;
import com.atguigu.lease.web.admin.service.AttrKeyService;
import com.atguigu.lease.web.admin.service.AttrValueService;
import com.atguigu.lease.web.admin.vo.attr.AttrKeyVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Stream;


@Tag(name = "房间属性管理")
@RestController
@RequestMapping("/admin/attr")
public class AttrController {

    @Autowired
    private AttrKeyService keyService;
    @Autowired
    private AttrValueService valueService;



    @Operation(summary = "新增或更新属性名称")
    @PostMapping("key/saveOrUpdate")
    public Result saveOrUpdateAttrKey(@RequestBody AttrKey attrKey) {
        keyService.saveOrUpdate(attrKey);
        return Result.ok();
    }

    @Operation(summary = "新增或更新属性值")
    @PostMapping("value/saveOrUpdate")
    public Result saveOrUpdateAttrValue(@RequestBody AttrValue attrValue) {
        valueService.saveOrUpdate(attrValue);
        return Result.ok();
    }

    @Operation(summary = "查询全部属性名称和属性值列表")
    @GetMapping("list")
    public Result<List<AttrKeyVo>> listAttrInfo() {

        //1、查询到所有的key
        List<AttrKey> keyList = keyService.list();

        //2、将keylist的key转换成attrKeyVo对象的,并添加到keyvolist中
        List<AttrKeyVo> keyVoList = keyList.stream().map(key -> {
            // 3、创建一个新的AttrKeyVo对象
            AttrKeyVo attrKeyVo = new AttrKeyVo();
            // 4、获取key对象的ID
            Long id = key.getId();
            //5、将key对象的属性复制到attrKeyVo对象中
            BeanUtils.copyProperties(key,attrKeyVo);
            //6、查询与当前key对象ID相匹配的属性值列表
            //lambdaQuery返回一个lambdaQueryWrapper对象，对象可以使用mysql的所有语法
            List<AttrValue> attrValueIdList = valueService.lambdaQuery().in(AttrValue::getAttrKeyId, id)
            .list();
            //7、将查询到的属性值列表设置到attrKeyVo对象的属性中
            attrKeyVo.setAttrValueList(attrValueIdList);
            //8、返回转换后的attrKeyVo对象
            return attrKeyVo;
        }).toList();
        //9、将keyVoList集合返回给前端
        return Result.ok(keyVoList);
    }

    @Operation(summary = "根据id删除属性名称")
    @DeleteMapping("key/deleteById")
    public Result removeAttrKeyById(@RequestParam Long attrKeyId) {
        keyService.removeById(attrKeyId);
        return Result.ok();
    }

    @Operation(summary = "根据id删除属性值")
    @DeleteMapping("value/deleteById")
    public Result removeAttrValueById(@RequestParam Long id) {
        valueService.removeById(id);
        return Result.ok();
    }

}
